#include "task.h"
#include "app.h"

extern struct task tasks[];

static uint8_t _get_task_id (task_id task_bit)
{
    uint8_t i;
    for (i = 0; i < get_task_numbers(); ++i)
    {
        if(tasks[i].id == task_bit )
        {
            return i;
        }
    }
    return TASK_INVALID;
}

void task_start(task_id task_bit)
{
    uint8_t t_id;
    t_id = _get_task_id(task_bit);
    if(t_id == TASK_INVALID )
    {
        return;
    }

    tasks[t_id].flags = ALIVE;
}

void task_stop(task_id  task_bit)
{
    uint8_t t_id;
    t_id = _get_task_id(task_bit);
    if(t_id == TASK_INVALID )
    {
        return;
    }

    tasks[t_id].flags = UNALIVE;
}

void task_sig_send(task_id task_bit, uint8_t sig)
{
    uint8_t t_id;
    t_id = _get_task_id(task_bit);
    if(t_id == TASK_INVALID )
    {
        return;
    }
    tasks[t_id].signal |= sig;
    task_start(task_bit);

}

uint8_t task_sig_get(task_id task_bit)
{
    uint8_t t_id;
    uint8_t tmp;
    t_id = _get_task_id(task_bit);
    if(t_id == TASK_INVALID )
    {
        return 0;
    }
    tmp = tasks[t_id].signal;
    tasks[t_id].signal = 0;
    return tmp;
}

void task_handle(void)
{
    uint8_t i;
    for (i = 0; i < get_task_numbers(); ++i)
    {
        if(tasks[i].flags  == ALIVE )
        {
            tasks[i].flags = UNALIVE;
            tasks[i].handle(tasks[i].args);
        }
        else if(tasks[i].flags  == ALWAYS_ALIVE )
        {
            tasks[i].handle(tasks[i].args);
        }
    }
}

